const { series } = require("gulp");
const gulp = require("gulp");
var sass = require("gulp-sass")(require("sass"));

const open = require("open");
const connect = require("gulp-connect");

function getLocalIP() {
  var os = require("os");
  var ifaces = os.networkInterfaces();
  for (var dev in ifaces) {
    for (let i = 0; i < ifaces[dev].length; i++) {
      let details = ifaces[dev][i];
      if (details.family == "IPv4") {
        return details.address;
      }
    }
  }
}

let timer2;
function sassTocss(cb) {
  clearTimeout(timer2);
  timer2 = setTimeout(() => {
    gulp
      .src("src1/scss/*.scss")
      .pipe(sass({ outputStyle: "expanded" }).on("error", sass.logError))
      .pipe(gulp.dest("src1/css"));
  }, 1000);
  cb();
}

function webserver(cb) {
  let ip = getLocalIP();
  connect.server({
    livereload: true,
    port: 8080,
    host: ip,
  });
  console.log(ip);
  open("http://" + ip + ":8080/src1");
  //监听 script 下边的 js 文件，并执行 script 方法
  gulp.watch("src1/scss/*.scss", sassTocss);
  gulp.watch("src1/**/*", reload);
  //这样文件变更了就会自动构建
  cb();
}

let timer;
function reload(cb) {
  clearTimeout(timer);
  timer = setTimeout(() => {
    gulp.src("src1/index.html").pipe(connect.reload());
  }, 1000);
  cb();
}

exports.serve = series(webserver);
